/**
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 2010  Sean Beecroft

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

 * @version 1.10 2010-01-01
 * @author Sean Beecroft
 */
package yawiki.server.symbols;

import java.io.*;
import java.util.*;


import yawiki.server.application.Globals;
import yawiki.server.filters.Filter;
import yawiki.server.parsers.Parser;
import yawiki.server.util.Toolbox;

public class Document {

    private String title = "Title";
    private String page = "";
    private Vector citations = new Vector();
    private Vector elements = new Vector();
    private Vector filters = new Vector();
    private Section root = new Section();
    public static final int CHAIN_HEAD_DEFAULT = 1;
    int pos = 0;
    int chainHead = CHAIN_HEAD_DEFAULT;
    String data = null;
    boolean bIsRedirect = false;
    String redirect = "";

    public void addFilter(Filter filter) {
        filters.addElement(filter);
    }

    public Enumeration getFilters() {
        return filters.elements();
    }

    public Document(String page, String data) {
        this.data = data;
        this.page = page;
        ////////////////////////////// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        parse(data);

        addCitation(new Citation("020171499X", Citation.UNSOURCED));
        addCitation(new Citation("0596002874", Citation.UNSOURCED));
        addCitation(new Citation("019521983X", Citation.UNSOURCED));

    }

    public void addCitation(Citation cite) {
        citations.addElement(cite);
    }

    public String getRedirect() {
        return Parser.parseRedirect(data);
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public boolean isRedirect() {
        return Toolbox.isRedirect(data);
    }

    public void parse(String data) {

        try {

            Section ret = null;
            //System.out.println("parse");

            Parser.parseISBN(data);

            final java.io.BufferedReader bufferedReader = new java.io.BufferedReader(new StringReader(data));
            String S = null;
            Section wikiElement = null;
            String text = "";
            String title = "";

            ret = new Section();
            ret.setChainHead(Document.CHAIN_HEAD_DEFAULT);
            boolean firstItem = true;
            String introS = "";

            while ((S = bufferedReader.readLine()) != null) {
                if (S.startsWith("=")) {
                    firstItem = false;
                    if (wikiElement != null) {
                        if (Filter.filterElement(wikiElement)) {
                            elements.addElement(wikiElement);
                        }
                    }
                    int level = Parser.parseLevel(S);

                    wikiElement = new Section();
                    wikiElement.setChainHead(chainHead);
                    wikiElement.setLevel(level);
                    String t = Parser.parseTitle(S);

                    wikiElement.setTitle(t);

                } else if (firstItem == true) {
                    introS += S + "\n";
                } else {
                    if (wikiElement != null) {
                        String buf = wikiElement.getText() + "\n" + S;
                        wikiElement.setText(buf);
                    }
                }
            }

            if (introS != null) {
                Section intro = new Section();
                intro.setTitle("Introduction");
                intro.setLevel(1);
                intro.setText("\n\n" + introS);
                elements.insertElementAt(intro, 0);
            }

            if (wikiElement != null) {
                if (!elements.contains(wikiElement)) {
                    if (Filter.filterElement(wikiElement)) {
                        elements.addElement(wikiElement);
                    }
                }
            }

        } catch (Exception ex) {

            System.out.println("parse:" + ex);
            ex.printStackTrace();
        }
    }

    public String makeBodyHTML() {
        try {
            String body = "";

            Enumeration e = elements.elements();

            int justInCase = 0;
            int num = 0;
            String page = "";

            while (e.hasMoreElements()) {
                try {
                    Section we = (Section) e.nextElement();

                    we.setChainHead(chainHead);
                    body += "<HR>\n";
                    body += "<A NAME=\"" + (num++) + "\"></A><P ALIGN=RIGHT><A HREF=\"http://" + Globals.domain + Globals.context + "editor.jnlp?page=" + this.page + "\">edit</A> <A HREF=\"#top\">top</A></P>\n";
                    body += "<FONT SIZE=4>" + we.getTitle() + "</FONT>\n";
                    String s = we.getText();

                    if (we.getTitle().indexOf("Related Books") != -1) {
                        body += "" + s + "";
                    } else {
                        String subText = Parser.parse(s); //processWikiText(s, we);
                        body += "" + subText + "";
                    }

                    justInCase++;
                    if (justInCase > 200) {
                        return "Heap Error";
                    }


                } catch (Exception ex) {
                    System.out.println("Process HTML BOdy failed:" + ex);
                }
            }

            return body;
        } catch (Exception ex) {

            System.out.println("makeBodyHTML" + ex);
            ex.printStackTrace();
        }
        return "Unable to make body HTML";
    }

    public String toHTML() {
        String s = "<!-- " + System.currentTimeMillis() + " -->\n";
        try {
            if (root == null) {
                return "{root is null}\n";
            }
            root.setChainHead(chainHead);
            Section relatedBooks = new Section();
            relatedBooks.setParent(root);
            relatedBooks.setLevel(2);
            relatedBooks.setTitle("Related Books");
            String theBooks = getBooksHTML();
            String text = "<TABLE WIDTH=100%><TR><TD>" + theBooks + "</TD></TR></TABLE>";
            text += "\n";
            relatedBooks.setText(text);
            s += "<TABLE WIDTH=90% BORDER=0><TR><TD>";

            elements.addElement(relatedBooks);

            Enumeration e = elements.elements();
            int justInCase = 0;
            int num = 0;

            while (e.hasMoreElements()) {
                try {
                    Section we = (Section) e.nextElement();

                    we.setChainHead(chainHead);
                    s += "\n";
                    s += Toolbox.tocTab(we.getLevel()) + "<A HREF=\"#" + (num++)
                            + "\"><FONT SIZE=4>" + we.getTitle()
                            + "</FONT></A><BR>\n";

                    justInCase++;
                    if (justInCase > 300) {
                        break;
                    }
                } catch (Exception ex) {
                    System.out.println("Process HTML Body failed:" + ex);
                }
            }
            s += "</P></TD><TR></TABLE>";
            s += "<!-- Begin BODY -->\n";
            s += makeBodyHTML();
            s += "<!-- End Body -->\n";

        } catch (Exception ex) {
            System.out.println("toHTML()" + ex);
            ex.printStackTrace();
        }
        return s;
    }

    public String getBooksHTML() {
        Enumeration e = Parser.parseISBN(data);
        String html = "";
        int count = 0;
        boolean on = true;
        int justInCase = 0;

        while (e.hasMoreElements()) {
            String isbn = (String) e.nextElement();

            if (count == 0) {
                html += "<TR><TD><CENTER>";
                on = false;
            }

            html += "<iframe src=\"http://rcm-ca.amazon.ca/e/cm?t=yetanotherwik-20&o=15&p=8&l=as1&asins="
                    + isbn
                    + "&fc1=000000&IS2=1&lt1=_blank&lc1=0000FF&bc1=FFFFFF&bg1=FFFFFF&f=ifr\" style=\"width:120px;height:240px;\" scrolling=\"no\" marginwidth=\"0\" marginheight=\"0\" frameborder=\"0\"></iframe>\n";

            if (count++ >= 4) {
                html += "</CENTER></TD></TR>";
                count = 0;
                on = true;
            }

            justInCase++;
            if (justInCase > 200) {
                break;
            }
        }

        if (!on) {
            html += "</CENTER></TD></TR>";
        }

        return html;
    }
}

